package top.itmeans.yes.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import top.itmeans.yes.dto.ProductParam;
import top.itmeans.yes.dto.ProductQueryParam;
import top.itmeans.yes.dto.ProductResult;
import top.itmeans.yes.entity.*;
import top.itmeans.yes.mapper.*;
import top.itmeans.yes.service.ProductService;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 玉货信息表	 服务实现类
 * </p>
 *
 * @author Yiming.Cao
 * @since 2022-05-05
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProductServiceImpl.class);
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductFullReductionMapper productFullReductionMapper;
    @Resource
    private SkuStockMapper skuStockMapper;
    @Resource
    private ProductAttributeValueMapper productAttributeValueMapper;
    @Resource
    private SubjectProductRelationMapper subjectProductRelationMapper;
    @Resource
    private PreferenceAreaProductRelationMapper preferenceAreaProductRelationMapper;
    @Resource
    private ProductVertifyRecordMapper productVertifyRecordMapper;

    @Override
    public int create(ProductParam productParam) {
        int count;
        //创建商品
        productParam.setId(null);
        productMapper.insert(productParam);
        //根据促销类型设置价格：会员价格、阶梯价格、满减价格
        Long productId = productParam.getId();
        //满减价格
        relateAndInsertList(productFullReductionMapper, productParam.getProductFullReductionList(), productId);
        //处理sku的编码
        handleSkuStockCode(productParam.getSkuStockList(),productId);
        //添加sku库存信息
        relateAndInsertList(skuStockMapper, productParam.getSkuStockList(), productId);
        //添加商品参数,添加自定义商品规格
        relateAndInsertList(productAttributeValueMapper, productParam.getProductAttributeValueList(), productId);
        //关联专题
        relateAndInsertList(subjectProductRelationMapper, productParam.getSubjectProductRelationList(), productId);
        //关联优选
        relateAndInsertList(preferenceAreaProductRelationMapper, productParam.getPreferenceAreaProductRelationList(), productId);
        count = 1;
        return count;
    }

    private void handleSkuStockCode(List<SkuStock> skuStockList, Long productId) {
        if(CollectionUtils.isEmpty(skuStockList)) {
            return;
        }
        for(int i=0;i<skuStockList.size();i++){
            SkuStock skuStock = skuStockList.get(i);
            if(StringUtils.isEmpty(skuStock.getSkuCode())){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i+1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }

    @Override
    public ProductResult getUpdateInfo(Long id) {
        return productMapper.getUpdateInfo(id);
    }

    @Override
    public int update(Long id, ProductParam productParam) {
        int count;
        //更新商品信息
        Product product = productParam;
        product.setId(id);
        productMapper.updateById(product);
        //满减价格
        LambdaQueryWrapper<ProductFullReduction> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductFullReduction::getProductId,id);
        productFullReductionMapper.delete(queryWrapper);
        relateAndInsertList(productFullReductionMapper, productParam.getProductFullReductionList(), id);
        //修改sku库存信息
        handleUpdateSkuStockList(id, productParam);
        //修改商品参数,添加自定义商品规格
        LambdaQueryWrapper<ProductAttributeValue> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(ProductAttributeValue::getProductId,id);
        productAttributeValueMapper.delete(queryWrapper2);
        relateAndInsertList(productAttributeValueMapper, productParam.getProductAttributeValueList(), id);
        //关联专题
        LambdaQueryWrapper<SubjectProductRelation> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(SubjectProductRelation::getProductId,id);
        subjectProductRelationMapper.delete(queryWrapper3);
        relateAndInsertList(subjectProductRelationMapper, productParam.getSubjectProductRelationList(), id);
        //关联优选
        LambdaQueryWrapper<PreferenceAreaProductRelation> queryWrapper4 = new LambdaQueryWrapper<>();
        queryWrapper4.eq(PreferenceAreaProductRelation::getProductId,id);
        preferenceAreaProductRelationMapper.delete(queryWrapper4);
        relateAndInsertList(preferenceAreaProductRelationMapper, productParam.getPreferenceAreaProductRelationList(), id);
        count = 1;
        return count;
    }

    private void handleUpdateSkuStockList(Long id, ProductParam productParam) {
        //当前的sku信息
        List<SkuStock> currSkuList = productParam.getSkuStockList();
        //当前没有sku直接删除
        if(CollUtil.isEmpty(currSkuList)){
            LambdaQueryWrapper<SkuStock> skuStockLambdaQueryWrapper = new LambdaQueryWrapper<>();
            skuStockLambdaQueryWrapper.eq(SkuStock::getProductId,id);
            skuStockMapper.delete(skuStockLambdaQueryWrapper);
            return;
        }
        //获取初始sku信息
        LambdaQueryWrapper<SkuStock> skuStockLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        skuStockLambdaQueryWrapper2.eq(SkuStock::getProductId,id);
        List<SkuStock> oriStuList = skuStockMapper.selectList(skuStockLambdaQueryWrapper2);
        //获取新增sku信息
        List<SkuStock> insertSkuList = currSkuList.stream().filter(item->item.getId()==null).collect(Collectors.toList());
        //获取需要更新的sku信息
        List<SkuStock> updateSkuList = currSkuList.stream().filter(item->item.getId()!=null).collect(Collectors.toList());
        List<Long> updateSkuIds = updateSkuList.stream().map(SkuStock::getId).collect(Collectors.toList());
        //获取需要删除的sku信息
        List<SkuStock> removeSkuList = oriStuList.stream().filter(item-> !updateSkuIds.contains(item.getId())).collect(Collectors.toList());
        handleSkuStockCode(insertSkuList,id);
        handleSkuStockCode(updateSkuList,id);
        //新增sku
        if(CollUtil.isNotEmpty(insertSkuList)){
            relateAndInsertList(skuStockMapper, insertSkuList, id);
        }
        //删除sku
        if(CollUtil.isNotEmpty(removeSkuList)){
            List<Long> removeSkuIds = removeSkuList.stream().map(SkuStock::getId).collect(Collectors.toList());
            skuStockMapper.deleteBatchIds(removeSkuList);
        }
        //修改sku
        if(CollUtil.isNotEmpty(updateSkuList)){
            for (SkuStock SkuStock : updateSkuList) {
                skuStockMapper.updateById(SkuStock);
            }
        }

    }

    @Override
    public Page<Product> list(ProductQueryParam productQueryParam, Integer pageSize, Integer pageNum) {
        Page<Product> productPage = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Product> productQueryWrapper = new LambdaQueryWrapper<>();
        if (productQueryParam.getPublishStatus() != null) {
            productQueryWrapper.eq(Product::getPublishStatus,productQueryParam.getPublishStatus());
        }
        if (productQueryParam.getVerifyStatus() != null) {
            productQueryWrapper.eq(Product::getVerifyStatus,productQueryParam.getVerifyStatus());
        }
        if (!StringUtils.isEmpty(productQueryParam.getKeyword())) {
            productQueryWrapper.like(Product::getName,productQueryParam.getKeyword());
        }
        if (productQueryParam.getProductCategoryId() != null) {
            productQueryWrapper.eq(Product::getProductCategoryId,productQueryParam.getProductCategoryId());
        }
        return productMapper.selectPage(productPage,productQueryWrapper);
    }

    @Override
    public int updateVerifyStatus(List<Long> ids, Integer verifyStatus, String detail) {
        Product product = new Product();
        product.setVerifyStatus(verifyStatus);
        LambdaQueryWrapper<Product> productQueryWrapper = new LambdaQueryWrapper<>();
        productQueryWrapper.in(Product::getId,ids);
        List<ProductVertifyRecord> list = new ArrayList<>();
        int count = productMapper.update(product, productQueryWrapper);
        //修改完审核状态后插入审核记录
        for (Long id : ids) {
            ProductVertifyRecord record = new ProductVertifyRecord();
            record.setProductId(id);
            record.setCreateTime(LocalDateTime.now());
            record.setDetail(detail);
            record.setStatus(verifyStatus);
            record.setVertifyMan("test");
            productVertifyRecordMapper.insert(record);
        }
        return count;
    }

    @Override
    public int updatePublishStatus(List<Long> ids, Integer publishStatus) {
        Product record = new Product();
        record.setPublishStatus(publishStatus);
        LambdaQueryWrapper<Product> productQueryWrapper = new LambdaQueryWrapper<>();
        productQueryWrapper.in(Product::getId,ids);
        return productMapper.update(record, productQueryWrapper);
    }

    @Override
    public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
        Product record = new Product();
        record.setRecommandStatus(recommendStatus);
        LambdaQueryWrapper<Product> productQueryWrapper = new LambdaQueryWrapper<>();
        productQueryWrapper.in(Product::getId,ids);
        return productMapper.update(record, productQueryWrapper);
    }

    @Override
    public int updateNewStatus(List<Long> ids, Integer newStatus) {
        Product record = new Product();
        record.setNewStatus(newStatus);
        LambdaQueryWrapper<Product> productQueryWrapper = new LambdaQueryWrapper<>();
        productQueryWrapper.in(Product::getId,ids);
        return productMapper.update(record, productQueryWrapper);
    }

    @Override
    public int updateDeleteStatus(List<Long> ids, Integer deleteStatus) {
        Product record = new Product();
        record.setDeleteStatus(deleteStatus);
        LambdaQueryWrapper<Product> productQueryWrapper = new LambdaQueryWrapper<>();
        productQueryWrapper.in(Product::getId,ids);
        return productMapper.update(record, productQueryWrapper);
    }

    @Override
    public List<Product> list(String keyword) {
        LambdaQueryWrapper<Product> productQueryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(keyword)){
            productQueryWrapper.like(Product::getName,keyword);
        }
        return productMapper.selectList(productQueryWrapper);
    }

    /**
     * 建立和插入关系表操作
     *
     * @param dao       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object dao, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)) {
                return;
            }
            for (Object item : dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long) null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
                Method insert = dao.getClass().getMethod("insert", Object.class);
                insert.invoke(dao, item);
            }
            /*
            Method insertList = dao.getClass().getMethod("insertList", List.class);
            insertList.invoke(dao, dataList);
            */
        } catch (Exception e) {
            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

}
